<?php
namespace app\userweb\controller;

use app\apishop\controller\Product;
use think\Config;
use think\Controller;
use think\Db;
use think\Request;
use think\Session;

class Homepage extends Controller {

    /**
     * @writer:wuqiubai
     * @DateTime:2018-01-26
     * @rewriter:xx
     * @rewriter_date:
     * @description:首页
     * @param:[]
     * @return[$result]
     */
    public function getList(){
        $data  = request()->post();
        if (!empty($data['city']) && $data['city'] == 'undefined'){
            $data['city'] = '';
        }
        if (!empty($data['user_id']) && array_key_exists('search',$data) && array_key_exists('classify',$data)){      //登录后
            if (!empty($data['city'])){
                $city = $data['city'];
            }
            $city = Db::table('user')->where('id',$data['user_id'])->value('city');
            if (!empty($data['search']) && empty($data['classify'])){
                $where  = [
                    'P.name|S.name'       => ['like','%'.trim($data['search']).'%'],
                    'S.is_open'           => 1,
                    'SE.send_area'        => $city,
                    'S.check_status'      => 2,
                    'P.status'            => 1,
                    'P.is_shelves'        => 1,
                ];
            }elseif(empty($data['search']) && !empty($data['classify'])){
                $info = explode(',',$data['classify']);
                if (!empty($info[2])){
                    $where  = [
                        'S.is_open'           => 1,
                        'S.check_status'      => 2,
                        'SE.send_area'        => $city,
                        'P.'.$info[0]         => $info[1],
                        'P.'.$info[2]         => $info[3],
                        'P.status'            => 1,
                        'P.is_shelves'        => 1,
                    ];
                }else{
                    $where  = [
                        'S.is_open'           => 1,
                        'S.check_status'      => 2,
                        'SE.send_area'        => $city,
                        'P.'.$info[0]         => $info[1],
                        'P.status'            => 1,
                        'P.is_shelves'        => 1,
                    ];
                }
                $where1 = [
                    'S.is_open'           => 1,
                    'S.check_status'      => 2,
                    'SE.send_area'        => $city,
                    'P.'.$info[0]         => $info[1],
                    'P.status'            => 1,
                    'P.is_shelves'        => 1,
                ];
                $brands = Db::table('product')
                    ->alias('P')
                    ->field('BD.id, BD.name, BD.name_english')
                    ->join('supplier S'  ,'S.id  = P.supplier')
                    ->join('supplier_send_manage SE','SE.supplier_id = P.supplier')
                    ->join('base_data BD','BD.id = P.brand_id')
                    ->where($where1)
                    ->group('BD.id')
                    ->select();
                $arr = array();
                for($i=0;$i<count($brands);$i++)
                {
                    if(!isset($arr[$brands[$i]['id']]))
                    {
                        $arr[$brands[$i]['id']] = $brands[$i];
                    }
                }
                $brands = array_values($arr);
            }else {
                $where  = [
                    'S.is_open'           => 1,
                    'S.check_status'      => 2,
                    'SE.send_area'        => $city,
                ];
            }
            $list = Db::table('supplier')
                ->alias('S')
                ->field('S.id, S.name, S.image, S.star')
                ->join('product P','P.supplier = S.id')
                ->join('supplier_send_manage SE','SE.supplier_id = S.id')
                ->where($where)
                ->order('S.star desc')
                ->group('S.id')
                ->paginate(9,false,['path'=>'javascript:AjaxPage([PAGE]);','type'=>'BootstrapDetailed']);
            $supplier           = $list->toArray();
            /*if (empty($data['search'])){
                foreach ($supplier['data'] as $k=>$v){
                    $discounts  = Db::table('discount')
                        ->field('name,start_time,end_time')
                        ->where(['supplier_id'=>$v['id'], 'status'=>1])
                        ->select();
                    if ($discounts){
                        foreach ($discounts as $kk=>$vv){
                            $time       = strtotime("now");
                            $start_time = strtotime($vv['start_time']);
                            $end_time   = strtotime($vv['end_time']);
                            if ($start_time <= $time && $time <= $end_time){
                                $supplier['data'][$k]['name'] = $vv['name'];
                            }
                        }
                    }
                }
            }*/
        }elseif (empty($data['user_id']) && array_key_exists('search',$data) && array_key_exists('classify',$data)){  //游客模式
            if (!empty($data['search']) && empty($data['classify'])){
                if (!empty($data['city'])){
                    $where  = [
                        'P.name|S.name'       => ['like','%'.trim($data['search']).'%'],
                        'S.is_open'           => 1,
                        'S.check_status'      => 2,
                        'SE.send_area'        => $data['city'],
                        'P.status'            => 1,
                        'P.is_shelves'        => 1,
                    ];
                }else{
                    $where  = [
                        'P.name|S.name'     => ['like','%'.trim($data['search']).'%'],
                        'S.is_open'           => 1,
                        'S.check_status'      => 2,
                        'P.status'            => 1,
                        'P.is_shelves'        => 1,
                    ];
                }
            }elseif(empty($data['search']) && !empty($data['classify'])){
                $info = explode(',',$data['classify']);
                if (!empty($info[2])){
                    if (!empty($data['city'])){
                        $where  = [
                            'S.is_open'           => 1,
                            'S.check_status'      => 2,
                            'SE.send_area'        => $data['city'],
                            'P.'.$info[0]         => $info[1],
                            'P.'.$info[2]         => $info[3],
                            'P.status'            => 1,
                            'P.is_shelves'        => 1,
                        ];
                    }else{
                        $where  = [
                            'S.is_open'           => 1,
                            'S.check_status'      => 2,
                            'P.'.$info[0]         => $info[1],
                            'P.'.$info[2]         => $info[3],
                            'P.status'            => 1,
                            'P.is_shelves'        => 1,
                        ];
                    }
                }else{
                    if (!empty($data['city'])){
                        $where  = [
                            'S.is_open'           => 1,
                            'S.check_status'      => 2,
                            'SE.send_area'        => $data['city'],
                            'P.'.$info[0]         => $info[1],
                            'P.status'            => 1,
                            'P.is_shelves'        => 1,
                        ];
                    }else{
                        $where  = [
                            'S.is_open'           => 1,
                            'S.check_status'      => 2,
                            'P.'.$info[0]         => $info[1],
                            'P.status'            => 1,
                            'P.is_shelves'        => 1,
                        ];
                    }
                }
                if (!empty($data['city'])){
                    $where1 = [
                        'S.is_open'           => 1,
                        'S.check_status'      => 2,
                        'SE.send_area'        => $data['city'],
                        'P.'.$info[0]         => $info[1],
                        'P.status'            => 1,
                        'P.is_shelves'        => 1,
                    ];
                }else{
                    $where1 = [
                        'S.is_open'           => 1,
                        'S.check_status'      => 2,
                        'P.'.$info[0]         => $info[1],
                        'P.status'            => 1,
                        'P.is_shelves'        => 1,
                    ];
                }
                $brands = Db::table('product')
                    ->alias('P')
                    ->field('BD.id, BD.name, BD.name_english')
                    ->join('supplier S'  ,'S.id  = P.supplier')
                    ->join('supplier_send_manage SE','SE.supplier_id = P.supplier')
                    ->join('base_data BD','BD.id = P.brand_id')
                    ->where($where1)
                    ->group('BD.id')
                    ->select();
                $arr = array();
                for($i=0;$i<count($brands);$i++)
                {
                    if(!isset($arr[$brands[$i]['id']]))
                    {
                        $arr[$brands[$i]['id']] = $brands[$i];
                    }
                }
                $brands = array_values($arr);

            }else {
                if (!empty($data['city'])){
                    $where  = [
                        'S.is_open'           => 1,
                        'SE.send_area'        => $data['city'],
                        'S.check_status'      => 2,
                    ];
                }else{
                    $where  = [
                        'S.is_open'           => 1,
                        'S.check_status'      => 2,
                    ];
                }
            }
            $list = Db::table('supplier')
                ->alias('S')
                ->field('S.id, S.name, S.image, S.star')
                ->join('product P','P.supplier = S.id')
                ->join('supplier_send_manage SE','SE.supplier_id = S.id')
                ->where($where)
                ->order('S.star desc')
                ->group('S.id')
                ->paginate(9,false,['path'=>'javascript:AjaxPage([PAGE]);','type'=>'BootstrapDetailed']);
            $supplier = $list->toArray();
            /*if (empty($data['search'])){
                foreach ($supplier['data'] as $k=>$v){
                    $discounts  = Db::table('discount')
                        ->field('name,start_time,end_time')
                        ->where(['supplier_id'=>$v['id'], 'status'=>1])
                        ->select();
                    if ($discounts){
                        foreach ($discounts as $kk=>$vv){
                            $time       = strtotime("now");
                            $start_time = strtotime($vv['start_time']);
                            $end_time   = strtotime($vv['end_time']);
                            if ($start_time <= $time && $time <= $end_time){
                                $supplier['data'][$k]['name'] = $vv['name'];
                            }
                        }
                    }
                }
            }*/
        }else{
            return json(Config::get('code.mistake'));
        }
        if ($supplier) {
            $result = Config::get('code.success');
            $result['supplier']     = $supplier;
            $result['paginate']     = $list->render();
            $result['brands']       = '';
            if (!empty($brands)){
                $result['brands']   = $brands;
            }
        } else {
            $result = Config::get('code.null');
        }
        return json($result);
    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-01-26
     * @rewriter:xx
     * @rewriter_date:
     * @description:默认数据(分类数据)
     * @param:[]
     * @return[$result]
     */
    public function getIni(){
        $data       = request()->post();
        if (!empty($data['supplier_id'])){
            $product = Db::table('product')
                ->field('category_id, type_id, small_type_id')
                ->where('supplier',$data['supplier_id'])
                ->where(['supplier'=>$data['supplier_id'], 'status'=>1, 'is_shelves'=>1])
                ->select();
            $info=[];
            foreach ($product as $k=>$v){
                $info[]   = $v['category_id'];
                $info[]   = $v['type_id'];
                $info[]   = $v['small_type_id'];
            }
            $info = array_unique($info);
            $info = array_filter($info);
            $categories = [];
            foreach ($info as $k=>$v){
                $base_data = Db::table('base_data')
                    ->where(['id'=>$v, 'type_menu'=>1, 'flag'=>1])
                    ->find();
                if ($base_data){
                    $categories[] = $base_data;
                }
            }
        }else{
            $categories = Db::table('base_data')->where(['type_menu'=>1, 'flag'=>1])->select();
        }
        if ($categories){
            $result['status']       = 200;
            $result['categories']   = $categories;
        }else{
            $result = Config::get('code.null');
        }
        return json($result);
    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-01-29
     * @rewriter:xx
     * @rewriter_date:
     * @description:商品规格,商家活动.
     * @param:[]
     * @return[$result]
     */
    public function productExtend(){
        $data = request()->post();
        if (!empty($data['product_id'])){
            $time  = date("Y-m-d H:i:s", time());
            $where  = [
                'D.product_id'        => $data['product_id'],
                'D.status'            => 1,
                'D.start_time'        => ['<=',$time],
                'D.end_time'          => ['>=',$time],
            ];
            $specification = Db::table('product_specification')
                ->field('id, price, packing_proportion, unit, specification, is_default')
                ->where('product_id',$data['product_id'])
                ->order('is_default desc')
                ->select();
            $discount = Db::table('discount')
                ->alias('D')
                ->field('D.*,P.name as product_name')
                ->join('product P','P.id = D.product_id')
                ->where($where)
                ->find();
            if ($specification){
                $result = Config::get('code.success');
                if (!empty($discount)){
                    if ($discount['type'] == 1){
                        $result['discount']['name'] = '购买'.$discount['product_name'].'*'.$discount['condition_num'].'kg减'.$discount['relief_money'];
                    }else{
                        $result['discount']['name'] = '购买'.$discount['product_name'].'*'.$discount['condition_num'].'kg送'.$discount['give_product'];
                    }
                }else{
                    $result['discount']['name']             = '--';
                }
                /*if (!empty($discount)){
                    $info['name']           = '';
                    foreach ($discount as $k=>$v){
                        $info['name']           .= ','.$v['name'];
                    }
                    $info['name']           = ltrim($info['name'], ",");
                    $result['discount']     = $info;
                }else{
                    $result['discount']['name']             = '--';
                }*/
                foreach ($specification as $k=>$v){
                    $specification[$k]['price']    = number_format($v['price'],2,'.','');
                }
                $result['specification']    = $specification;
            }
        }else{
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-02-01
     * @rewriter:xx
     * @rewriter_date:
     * @description:商家的所有上架商品
     * @param:[]
     * @return[$result]
     */
    public function getProductAllList(){
        $data = request()->post();
        if (!empty($data['supplier_id']) && array_key_exists('search',$data) && array_key_exists('classify',$data)){
            if (!empty($data['classify'])){
                $info = explode(',',$data['classify']);
                if (!empty($info[2])){
                    $where  = [
                        'P.supplier'        => $data['supplier_id'],
                        'P.'.$info[0]       => $info[1],
                        'P.'.$info[2]       => $info[3],
                        'P.status'          => 1,
                        'P.is_shelves'      => 1,
                        'Ps.is_default'     => 1,
                    ];
                }else{
                    $where  = [
                        'P.supplier'        => $data['supplier_id'],
                        'P.'.$info[0]       => $info[1],
                        'P.status'          => 1,
                        'P.is_shelves'      => 1,
                        'Ps.is_default'     => 1,
                    ];
                }
                $where1 = [
                    'P.supplier'        => $data['supplier_id'],
                    'P.'.$info[0]       => $info[1],
                    'P.status'          => 1,
                    'P.is_shelves'      => 1,
                    'Ps.is_default'     => 1,
                ];
                $brands = Db::table('product')
                    ->alias('P')
                    ->field('BD.id, BD.name, BD.name_english')
                    ->join('base_data BD','BD.id = P.brand_id')
                    ->join('product_specification Ps','Ps.product_id = P.id')
                    ->where($where1)
                    ->select();
                $arr = array();
                for($i=0;$i<count($brands);$i++)
                {
                    if(!isset($arr[$brands[$i]['id']]))
                    {
                        $arr[$brands[$i]['id']] = $brands[$i];
                    }
                }
                $brands = array_values($arr);
            }else {
                $where  = [
                    'P.supplier'                => $data['supplier_id'],
                    'P.name'                    => ['like','%'.trim($data['search']).'%'],
                    'P.status'                  => 1,
                    'P.is_shelves'              => 1,
                    'Ps.is_default'             => 1,
                ];
            }
            $list = Db::table('product')
                ->alias('P')
                ->field('P.id, P.name as product_name, Ps.specification, Ps.packing_proportion, Ps.unit,
                    P.image as product_image, Ps.price')
                ->join('product_specification Ps','Ps.product_id = P.id')
                ->group('P.id')
                ->where($where)
                ->paginate(9,false,['path'=>'javascript:AjaxPage([PAGE]);','type'=>'BootstrapDetailed']);
            $product = $list->toArray();
            if ($product){
                foreach ($product['data'] as $k=>$v){
                    $product['data'][$k]['price']       =  number_format($v['price'],2,'.','');
                    $product['data'][$k]['is_collect']  =  0;
                    if ($v['packing_proportion'] == 1){
                        $product['data'][$k]['specification'] = $v['unit'];
                    }
                }
                if (!empty($data['user_id'])){
                    $collect_id =  Db::table('user_collect_product')
                        ->field('product_id')
                        ->where(['user_id'=>$data['user_id'],'is_del'=>0,'flag'=>1])
                        ->select();
                    foreach ($collect_id as $k=>$v){
                        foreach ($product['data'] as $kk=>$vv){
                            if ($v['product_id'] == $vv['id']){
                                $product['data'][$kk]['is_collect'] = 1;
                            }
                        }
                    }
                }
                $result = Config::get('code.success');
                $result['product']      = $product;
                $result['paginate']     = $list->render();
                $result['brands']       = '';
                if (!empty($brands)){
                    $result['brands']   = $brands;
                }
            }else{
                $result = Config::get('code.null');
            }
        }else{
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-02-27
     * @rewriter:xx
     * @rewriter_date:
     * @description:商家送货日期,用户地址,电话
     * @param:[]
     * @return[$result]
     */
    public function details(){
        $data = request()->post();
        if (!empty($data['user_id']) && !empty($data['supplier_id'])){
            $user               =   Db::table('user')->field('id, addr, phone, city, town')->where('id',$data['user_id'])->find();
            $send_time_type     =   Db::table('supplier')->where('id',$data['supplier_id'])->value('send_time_type');
            $is_open            =   Db::table('supplier')->where('id',$data['supplier_id'])->value('is_open');
            $send_date          =   '暂无配送';
            $discount           =   '--';
            if ($send_time_type == 1){                  //周配送.
                $send = Db::table('supplier_send_manage')
                    ->field('day, month, send_area')
                    ->where(['supplier_id'=>$data['supplier_id']])
                    ->where('month',0)
                    ->select();
                foreach ($send as $k=>$v){
                    if ($v['send_area'] == $user['city'] || $v['send_area'] == $user['town']){
                        $time = timeCompute(time());
                        $week = date('w');
                        if($week < $v['day']){
                            $time1 = ($v['day'] - $week)*24*60*60;
                            $date = strtotime($time['year'].'-'.$time['month'].'-'.$time['day'].' 00:00:00')+$time1;
                            $send_date = date("Y-m-d", $date);
                        }else{
                            $time1 = ( 7-($week-$v['day']))*24*60*60;
                            $date = strtotime($time['year'].'-'.$time['month'].'-'.$time['day'].' 00:00:00')+$time1;
                            $send_date = date("Y/m/d", $date);
                        }
                    }
                }
            }elseif ($send_time_type == 2){           //月配送.
                $send = Db::table('supplier_send_manage')
                    ->field('day, month, send_area')
                    ->where(['supplier_id'=>$data['supplier_id']])
                    ->where('month','<>',0)
                    ->select();
                foreach ($send as $k=>$v){
                    if ($v['send_area'] == $user['city'] || $v['send_area'] == $user['town']){
                        $time = timeCompute(time());
                        $send_date = $time['year'].'/'.$time['month'].'/'.$v['day'];
                    }
                }
            }

            $discount_info = Db::table('discount')
                ->field('id, type, condition_money, relief_money, start_time, end_time')
                ->where(['supplier_id'=>$data['supplier_id'], 'status'=>1])
                ->find();

            if ($discount_info){
                $time       = strtotime("now");
                $start_time = strtotime($discount_info['start_time']);
                $end_time   = strtotime($discount_info['end_time']);
                if ($start_time <= $time && $time <= $end_time){
                    if ($discount_info['type'] == 1){                //满减
//                        $discount           =   '满'.$discount_info['condition_money'].'减'.$discount_info['relief_money'];
                        $discount           =   '满减';
                        $condition_money    =   $discount_info['condition_money'];
                        $discount_money     =   $discount_info['relief_money'];
                    }elseif ($discount_info['type'] == 2){           //满送
//                        $discount           = '满'.$discount_info['condition_money'].'送'.$discount_info['give_product'];
                        $give               = Db::table('product_give')->where(['discount_id'=>$discount_info['id']])->find();
                        if ($give){
                            $give_product   = Db::table('product')->field('name, image')->where(['id'=>$give['product_id']])->find();
                            $give_product['count']   = $give['count'];
                        }
                        $discount           = '满送';
                        $condition_money    =   $discount_info['condition_money'];
                        $discount_money     = 0;
                    }
                }
            }
            $details['addr']            =  $user['addr'];
            $details['phone']           =  $user['phone'];
            $details['is_open']         =  $is_open;
            $details['send_area']       =  $send_date;
            $details['discount']        =  $discount;
            $details['discount_type']   =  $discount_info['type'];
            $details['condition_money'] =  $condition_money;
            $details['discount_money']  =  $discount_money;
            $details['give_product']    =  '';
            if (!empty($give_product)){
                $details['give_product']   =  $give_product;
            }
            if ($user){
                $result = Config::get('code.success');
                $result['details'] = $details;
            }else{
                $result = Config::get('code.null');
            }
        }else{
            $result = Config::get('code.mistake');
        }
        return json($result);
    }
    /**
     * @writer:wuqiubai
     * @DateTime:2018-03-03
     * @rewriter:xx
     * @rewriter_date:
     * @description: 小货郎客服电话
     * @param:[]
     * @return[$result]
     */
    public function service(){
        $data = request()->post();
        if (!empty($data['user_id'])){
            $city = Db::table('user')->where('id',$data['user_id'])->value('city');
            if (!empty($data['city'])){
               $city = $data['city'];
            }
            $service = Db::table('customer_service_district')
                ->alias('SD')
                ->join('customer_service CS','CS.id = SD.customer_service_id')
                ->field('CS.id, CS.name, CS.tel')
                ->where(['SD.city'=>$city,'CS.flag'=>1])
                ->select();
            if ($service){
                $result = Config::get('code.success');
                $result['service'] = $service;
            }else{
                $result = Config::get('code.null');
            }
        }else{
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    public function  contrastNow(){
        $data = request()->post();
        if (empty($data['user_id'])){
            $result = Config::get('code.mistake');
        }
        $id = $data['user_id'];
        $product = Db::table('order_user_cart')
                    ->where('user_id',$id)
                    ->select();
    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-03-06
     * @rewriter:xx
     * @rewriter_date:
     * @description: 判断商品是否存在 是否上架
     * @param:[]
     * @return[$result]
     */
    public function contrast(){
        $post = request()->post();
        if (!empty($post['user_id'])){
            $data = Db::table('order_user_cart')
                ->alias('c')
                ->field('s.id as supplier_id, s.is_open, s.name as supplier_name, s.image, s.minimum, s.send_time_type, 
                u.addr as address, u.phone as tel, u.city, u.town')
                ->join('supplier s','c.supplier_id = s.id')
                ->join('user u','c.user_id = u.id')
                ->where('user_id',$post['user_id'])
                ->group('c.supplier_id')
                ->select();
            $tax = Db::table('system_setting')->where('name','增值税比例')->value('value');
            $send_date  =   '暂无配送';
            foreach ($data as $k=>$v){
                if ($v['send_time_type'] == 1){                  //周配送.
                    $send = Db::table('supplier_send_manage')
                        ->field('day, month, send_area')
                        ->where(['supplier_id'=>$v['supplier_id']])
                        ->where('month',0)
                        ->select();
                    foreach ($send as $kk=>$vv){
                        if ($vv['send_area'] == $v['city'] || $vv['send_area'] == $v['town']){
                            $time = timeCompute(time());
                            $week = date('w');
                            if($week < $vv['day']){
                                $time1 = ($vv['day'] - $week)*24*60*60;
                                $date = strtotime($time['year'].'-'.$time['month'].'-'.$time['day'].' 00:00:00')+$time1;
                                $send_date = date("Y-m-d", $date);
                            }else{
                                $time1 = ( 7-($week-$vv['day']))*24*60*60;
                                $date = strtotime($time['year'].'-'.$time['month'].'-'.$time['day'].' 00:00:00')+$time1;
                                $send_date = date("Y/m/d", $date);
                            }
                        }
                    }
                }elseif ($v['send_time_type'] == 2){           //月配送.
                    $send = Db::table('supplier_send_manage')
                        ->field('day, month, send_area')
                        ->where(['supplier_id'=>$v['supplier_id']])
                        ->where('month','<>',0)
                        ->select();
                    foreach ($send as $kk=>$vv){
                        if ($vv['send_area'] == $v['city'] || $vv['send_area'] == $v['town']){
                            $time = timeCompute(time());
                            $send_date = $time['year'].'/'.$time['month'].'/'.$vv['day'];
                        }
                    }
                }
                $data[$k]['send_date']  = $send_date;
                $data[$k]['minimum']    = number_format($v['minimum'],2,'.','');
                $data[$k]['totalTax']   = 0;
                $data[$k]['totalMoney'] = 0;
                $totalTax   = 0;
                $totalMoney = 0;
                $product = Db::table('order_user_cart')
                    ->alias('c')
                    ->field('c.id as cart_id, c.product_specif_id, c.product_id, c.num, ps.packing_proportion as specification, ps.price, ps.unit,
                    p.is_shelves, p.name as product_name, p.image as product_image, p.stock, p.is_include_tax')
                    ->join('product p','c.product_id = p.id')
                    ->join('product_specification ps','c.product_specif_id = ps.id')
                    ->where('user_id',$post['user_id'])
                    ->where('supplier_id',$v['supplier_id'])
                    ->select();
                $goods = [];
                foreach ($product as $kk=>$vv){
                    if ($vv['is_include_tax'] == 0){
                        $product[$kk]['tax'] = (float)$tax * (float)$vv['price'];
                    }else{
                        $product[$kk]['tax'] = 0;
                    }
                    $total_price    = (float)$vv['price']            * (float)$vv['num'];
                    $total_tax      = (float)$product[$kk]['tax']    * (float)$vv['num'];
                    $total_money    = $total_price + $total_tax;
                    $product[$kk]['price']       = number_format($product[$kk]['price'],2,'.','');
                    $product[$kk]['total_tax']   = number_format($total_tax,2,'.','');
                    $product[$kk]['total_price'] = number_format($total_money,2,'.','');
                    $product[$kk]['is_discount'] = 0;
                    $discount = $this->discount($vv['product_id']);
                    if ($discount){
                        $product[$kk]['discount_type']      = $discount['type'];
                        $product[$kk]['condition_money']    = $discount['condition_money'];
                        $product[$kk]['condition_num']      = $discount['condition_num'];
                        $product[$kk]['discount_money']     = $discount['relief_money'];
                        $product[$kk]['give_product']       = $discount['give_product'];
                        $product[$kk]['discount_type']      = $discount['type'];
                        $product[$kk]['is_discount']        = 1;
                        if ($product[$kk]['num']>=$discount['condition_num']){
                            $much = floor($product[$kk]['num']/$discount['condition_num']);   //倍数
                            $product[$kk]['much'] = $much;
                            if ($discount['type'] == 1){        //满减
                                $discount_money = $much * $discount['relief_money'];
                                $pay_price      = $total_money - $discount_money;
                                $product[$kk]['discount']       = '￡'.number_format($discount_money,2,'.','');;
                                $product[$kk]['total_price']    = number_format($pay_price,2,'.','');
                            }
                            if ($discount['type'] == 2){        //满送
                                $product[$kk]['discount'] = $product[$kk]['give_product'].'*'.$much;
                            }
                        }else{
                            $product[$kk]['discount'] = '--';
                        }
                    }else{
                        $product[$kk]['discount'] = '--';
                    }
                    if (!empty($post['ids'])){
                        foreach ($post['ids'] as $value){
                            if ($vv['cart_id'] == (int)($value)){
                                $totalTax   += number_format($product[$kk]['total_tax'],2,'.','');
                                $totalMoney += number_format($product[$kk]['total_price'],2,'.','');
                                $data[$k]['totalTax']   = number_format($totalTax,2,'.','');
                                $data[$k]['totalMoney'] = number_format($totalMoney,2,'.','');
                                $goods[] = $product[$kk];
                            }
                        }
                    }else{
                        $totalTax   += number_format($product[$kk]['total_tax'],2,'.','');
                        $totalMoney += number_format($product[$kk]['total_price'],2,'.','');
                        $data[$k]['totalTax']   = number_format($totalTax,2,'.','');
                        $data[$k]['totalMoney'] = number_format($totalMoney,2,'.','');
                    }
                }
                if (!empty($post['ids'])){
                    if (!empty($goods)){
                        $data[$k]['product'] = $goods;
                    }else{
                        unset($data[$k]);
                    }
                }else{
                    $data[$k]['product'] = $product;
                }
            }
            $result = Config::get('code.success');
//            var_dump($data);
            $data = array_values($data);
            $result['buy_car'] = $data;
        }else{
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    public function delCart(){
        $post = request()->post();
        if (!empty($post['user_id']) && $post['delStr']){
            $where['user_id'] = $post['user_id'];
            $post['delStr']   = trim($post['delStr'],',');
            $arr = explode(',', $post['delStr']);
            $where['id'] = array('in',$arr);
            $Re = Db::name('order_user_cart')->where($where)->delete();
            if($Re){
                $result = config('code.success');
            }else{
                $result = config('code.error');
            }
        }else{
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    public function changCartNum(){
        $post = request()->post();
        if (!empty($post['user_id']) && !empty($post['goods'])){
            foreach ($post['goods'] as $k=>$v){
                foreach ($v['product'] as $kk=>$vv){
                    $cart = Db::table('order_user_cart')->where('id',$vv['cart_id'])->find();
                    if ($cart['num'] == $vv['num']){
                        $Re = true;
                    }else{
                        $Re = Db::table('order_user_cart')->where('id',$vv['cart_id'])->setField('num',$vv['num']);
                    }
                    if($Re){
                        $result = config('code.success');
                    }else{
                        return json(config('code.error'));
                    }
                }
            }
        }else{
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    public function orderNow(){
        $post = request()->post();
        if (!empty($post['user_id']) && $post['product_id'] && $post['num'] && $post['product_specif_id'] && $post['supplier_id']){
            $user           = Db::table('user')->where('id',$post['user_id'])->find();
            $supplier       = Db::table('supplier')->where('id',$post['supplier_id'])->find();
            $product        = Db::table('product')->where('id',$post['product_id'])->find();
            $product_info   = Db::table('product_specification')->where('id',$post['product_specif_id'])->find();
            $data           = [];
            $info = [
                'supplier_id'       => $supplier['id'],
                'is_open'           => $supplier['is_open'],
                'supplier_name'     => $supplier['name'],
                'image'             => $supplier['image'],
                'minimum'           => number_format($supplier['minimum'],2,'.',''),
                'send_time_type'    => $supplier['send_time_type'],
                'address'           => $user['addr'],
                'tel'               => $user['phone'],
                'city'              => $user['town'],
            ];
//            $data[] = $info;
            $tax = Db::table('system_setting')->where('name','增值税比例')->value('value');
            $send_date  =   '暂无配送';
            if ($supplier['send_time_type'] == 1){                  //周配送
                $where  = [
                    'supplier_id'     => $post['supplier_id'],
                    'month'           => 0,
                ];
            }elseif ($supplier['send_time_type'] == 2){             //月配送.
                $where  = [
                    'supplier_id'     => $post['supplier_id'],
                    'month'           => ['<>',0]
                ];
            }
            $send = Db::table('supplier_send_manage')
                ->field('day, month, send_area')
                ->where($where)
                ->select();
            foreach ($send as $k=>$v){
                if ($v['send_area'] == $user['city'] || $v['send_area'] == $user['town']){
                    $time = timeCompute(time());
                    $week = date('w');
                    if ($supplier['send_time_type'] == 1){                  //周配送
                        if($week < $v['day']){
                            $time1 = ($v['day'] - $week)*24*60*60;
                            $date = strtotime($time['year'].'-'.$time['month'].'-'.$time['day'].' 00:00:00')+$time1;
                            $send_date = date("Y-m-d", $date);
                        }else{
                            $time1 = ( 7-($week-$v['day']))*24*60*60;
                            $date = strtotime($time['year'].'-'.$time['month'].'-'.$time['day'].' 00:00:00')+$time1;
                            $send_date = date("Y/m/d", $date);
                        }
                    }elseif ($supplier['send_time_type'] == 2){             //月配送.
                        $send_date = $time['year'].'/'.$time['month'].'/'.$v['day'];
                    }
                }
            }
            $info['send_date']  = $send_date;
            $info['totalTax']   = 0;
            $info['totalMoney'] = 0;
            //整合商品的数据
            $goods = [
                'product_id'        => $product['id'],
                'product_name'      => $product['name'],
                'num'               => $post['num'],
                'specification'     => $product_info['packing_proportion'],
                'unit'              => $product_info['unit'],
                'product_image'     => $product['image'],
                'stock'             => $product['stock'],
                'is_shelves'        => $product['is_shelves'],
                'is_include_tax'    => $product['is_include_tax'],
                'price'             => number_format($product_info['price'],2,'.',''),
            ];
            if ($product['is_include_tax'] == 0){
                $goods['tax'] = (float)$tax * (float)$product_info['price'];
            }else{
                $goods['tax'] = 0;
            }
            $total_price    = (float)$product_info['price']  * (float)$post['num'];
            $total_tax      = (float)$goods['tax']           * (float)$post['num'];
            $total_money    = $total_price + $total_tax;
            $goods['total_tax']   = number_format($total_tax,2,'.','');
            $goods['total_price'] = number_format($total_money,2,'.','');
            $goods['is_discount'] = 0;
            $discount = $this->discount($product['id']);
            if ($discount){
                $goods['discount_type']      = $discount['type'];
                $goods['condition_money']    = $discount['condition_money'];
                $goods['condition_num']      = $discount['condition_num'];
                $goods['discount_money']     = $discount['relief_money'];
                $goods['discount_type']      = $discount['type'];
                $goods['give_product']       = $discount['give_product'];
                $goods['is_discount']        = 1;
                if ($goods['num']>=$discount['condition_num']){
                    $much = floor($goods['num']/$discount['condition_num']);   //倍数
                    $goods['much'] = $much;
                    if ($discount['type'] == 1){        //满减
                        $discount_money = $much * $discount['relief_money'];
                        $pay_price      = $total_money - $discount_money;
                        $goods['discount']       = '￡'.number_format($discount_money,2,'.','');;
                        $goods['total_price']    = number_format($pay_price,2,'.','');
                    }
                    if ($discount['type'] == 2){        //满送
                        $goods['discount'] = $goods['give_product'].'*'.$much;
                    }
                }else{
                    $goods['discount'] = '--';
                }
            }else{
                $goods['discount'] = '--';
            }
            $info1[] = $goods;
            $info['totalTax']   = $goods['total_tax'];
            $info['totalMoney'] = $goods['total_price'];
            $info['product']    = $info1;
            $data[] = $info;
            $result = Config::get('code.success');
            $result['buy_car'] = $data;
        }else{
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-03-08
     * @rewriter:xx
     * @rewriter_date:
     * @description:默认数据(优惠活动)
     * @param:[]
     * @return[$result]
     */
    public function discounts(){
        $data       = request()->post();
        $city = '';
        if (!empty($data['page_no'])){
            $pageNo     = $data['page_no'];
            $pageSize   = 5;
        }
        if (!empty($data['user_id']) && !empty($data['page_no'])){      //登录后显示的该附近的活动.
            $city = Db::table('user')->where('id',$data['user_id'])->value('city');
            if (!empty($data['city'])){
                $city = $data['city'];
            }
            $time  = date("Y-m-d H:i:s", time());
            $where  = [
                'SE.send_area'        => $city,
                'S.is_open'           => 1,
                'S.check_status'      => 2,
                'D.status'            => 1,
                'D.start_time'        => ['<=',$time],
                'D.end_time'          => ['>=',$time],
                'P.is_shelves'        => 1,
                'P.status'            => 1,
            ];
        }elseif(!empty($data['page_no'])){                              //游客模式
            $time  = date("Y-m-d H:i:s", time());
            $where  = [
                'S.is_open'           => 1,
                'S.check_status'      => 2,
                'D.status'            => 1,
                'D.start_time'        => ['<=',$time],
                'D.end_time'          => ['>=',$time],
                'P.is_shelves'        => 1,
                'P.status'            => 1,
            ];
            if (!empty($data['city'])){
                $city   = $data['city'];
                $where  = [
                    'S.is_open'           => 1,
                    'SE.send_area'        => $city,
                    'S.check_status'      => 2,
                    'D.status'            => 1,
                    'D.start_time'        => ['<=',$time],
                    'D.end_time'          => ['>=',$time],
                    'P.is_shelves'        => 1,
                    'P.status'            => 1,
                ];
            }
        }
        $discounts['list']  = Db::table('discount')
            ->alias('D')
            ->field('P.id,P.sale_num, D.name as discount_name, D.type, D.condition_num, D.relief_money, D.give_product, P.image, P.name as product_name, S.name as supplier_name,D.start_time,D.end_time')
            ->join('supplier S','S.id = D.supplier_id')
            ->join('product P','P.id = D.product_id')
            ->join('supplier_send_manage SE','SE.supplier_id = D.supplier_id')
            ->where($where)
            ->limit(($pageNo-1)*$pageSize,$pageSize)
            ->group('D.id')
            ->order('S.star desc')
			->order('P.sale_num desc')
            ->select();
        if (!empty($discounts['list'])){
            foreach ($discounts['list'] as $k=>$v){
                if ($v['type'] == 1){
                    $discounts['list'][$k]['discount_name'] = '购买'.$v['product_name'].'*'.$v['condition_num'].'kg减'.$v['relief_money'];
                }else{
                    $discounts['list'][$k]['discount_name'] = '购买'.$v['product_name'].'*'.$v['condition_num'].'kg送'.$v['give_product'];
                }
            }
        }
        $count = Db::table('discount')
            ->alias('D')
            ->join('supplier S','S.id = D.supplier_id')
            ->join('product P','P.id = D.product_id')
            ->join('supplier_send_manage SE','SE.supplier_id = D.supplier_id')
            ->group('D.id')
            ->where($where)
            ->count();
        $discounts['pageCount'] = ceil($count/$pageSize);
        if ($discounts){
            $result['status']       = 200;
            $result['discounts']    = $discounts;
        }else{
            $result = Config::get('code.null');
        }
        return json($result);
    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-03-08
     * @rewriter:xx
     * @rewriter_date:
     * @description:默认数据(轮播图)
     * @param:[]
     * @return[$result]
     */
    public function bannerList(){
        $bannerImage    = Db::table('carousel')->where('status',1)->value('image');
        $images         = explode(',', $bannerImage);
        if ($images){
            $result['status']          = 200;
            $result['bannerImages']    = $images;
        }else{
            $result = Config::get('code.null');
        }
        return json($result);
    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-03-08
     * @rewriter:xx
     * @rewriter_date:
     * @description: 小货郎 数据
     * @param:[]
     * @return[$result]
     */
    public function xhlData(){
        $tel    = Db::table('system_setting')->where('name','平台电话')->value('value');
        $phone    = Db::table('system_setting')->where('name','在线客服')->value('value');
        $email  = Db::table('system_setting')->where('name','平台邮箱')->value('value');
        $xhlData['tel']     = $tel;
        $xhlData['phone']     = $phone;
        $xhlData['email']   = $email;
        if ($xhlData){
            $result['status']     = 200;
            $result['xhlData']    = $xhlData;
        }else{
            $result = Config::get('code.null');
        }
        return json($result);
    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-03-08
     * @rewriter:xx
     * @rewriter_date:
     * @description: 小货郎 数据
     * @param:[]
     * @return[$result]
     */
    public function defaults(){
        $xhlData = [];
        $xhlData['tel']                = Db::table('system_setting')->where('name','平台电话')->value('value');
        $xhlData['email']              = Db::table('system_setting')->where('name','平台邮箱')->value('value');
        $xhlData['addr']               = Db::table('system_setting')->where('name','地址')->value('value');
        $xhlData['addr_english']       = Db::table('system_setting')->where('name','地址_英文')->value('value');
        $xhlData['manager']            = Db::table('system_setting')->where('name','联系人')->value('value');
        $xhlData['manager_english']    = Db::table('system_setting')->where('name','联系人_英文')->value('value');
        $xhlData['android_image']      = Db::table('system_setting')->where('name','用户二维码')->value('value');
        $xhlData['ios_image']          = Db::table('system_setting')->where('name','用户ios二维码')->value('value');
        $xhlData['content']            = Db::table('protocol')->where('type',4)->value('content');
        $xhlData['user_content']       = Db::table('protocol')->where('type',1)->value('content');
        if ($xhlData){
            $result['status']     = 200;
            $result['xhlData']    = $xhlData;
        }else{
            $result = Config::get('code.null');
        }
        return json($result);
    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-03-14
     * @rewriter:xx
     * @rewriter_date:
     * @description: 验证Token
     * @param:[]
     * @return[$result]
     */
    public function validToken(){
        $data = Request::instance()->post();
        $web_token = Db::table('user')->where('id',$data['user_id'])->value('web_token');
        if ($web_token){
            $result['status']     = 200;
            $result['web_token']  = $web_token;
        }else{
            $result = Config::get('code.null');
        }
        return json($result);
    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-03-15
     * @rewriter:xx
     * @rewriter_date:
     * @description: 全部删除失效商品
     * @param:[]
     * @return[$result]
     */
    public function delLoseProduct(){
        $data = Request::instance()->post();
        if (!empty($data['user_id'])&&!empty($data['type'])){
            if ($data['type'] == -1){       //失效
                $where  = ['U.user_id' => $data['user_id'], 'U.is_del' => 0, 'P.is_shelves' => ['<>',1]];
            }
            if ($data['type'] == 1){        //六个月前
                $time   = gainTime('month','-6');
                $year   = date('Y',$time);
                $month  = date('m',$time);
                $where  = [
                    'U.user_id'     => $data['user_id'],
                    'U.is_del'      => 0,
                    'U.year'        => ['<=',$year],
                    'U.month'       => ['<=',$month],
                    'P.is_shelves'  => ['<>',1]
                ];
            }
            if ($data['type'] == 2){        //一年前
                $time   = gainTime('month','-12');
                $year   = date('Y',$time);
                $where  = [
                    'U.user_id'     => $data['user_id'],
                    'U.is_del'      => 0,
                    'U.year'        => ['<=',$year],
                    'P.is_shelves'  => ['<>',1]
                ];
            }
            if ($data['type'] <-1 || $data['type'] >2){
                return json(Config::get('code.mistake'));
            }
            $res = Db::name('user_collect_product')
                ->alias('U')
                ->join('product P','P.id = U.product_id')
                ->where($where)
                ->setField('is_del',1);
            if ($res){
                $result = Config::get('code.success');
            }else{
                $result = Config::get('code.error');
            }
        }else{
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-04-13
     * @rewriter:xx
     * @rewriter_date:
     * @description: 优惠活动
     * @param:[]
     * @return[$result]
     */
    private function discount($product_id){
        $discount_info = Db::table('discount')
            ->field('id, type, condition_money, condition_num, ifNull(relief_money,0) as relief_money, give_product, start_time, end_time')
            ->where(['product_id'=>$product_id, 'status'=>1])
            ->find();
        $re = [];
        if ($discount_info){
            $time       = strtotime("now");
            $start_time = strtotime($discount_info['start_time']);
            $end_time   = strtotime($discount_info['end_time']);
            if ($start_time <= $time && $time <= $end_time){
                $re = $discount_info;
            }
        }
        return $re;
    }

    public function getDiscountData(){
        extract(input());
        $count = Db::table('discount d')
            ->join('supplier s','d.supplier_id = s.id','left')
            ->where(['status'=>1,'is_groom'=>2])
            ->where('start_time','<',date('Y-m-d H:i:s'))
            ->count();
        $data = Db::table('discount d')
            ->join('supplier s','d.supplier_id = s.id','left')
            ->where(['status'=>1,'is_groom'=>2])
            ->where('start_time','<',date('Y-m-d H:i:s'))
            ->field(['d.*','s.name'=>'shop_name','s.name_english'=>'shop_name_english'])
            ->page($page,1)
            ->order('add_time desc')
            ->select ();
        return json(['code'=>200,'msg'=>$data,'count'=>$count]);
    }
}